package com.power.structure.linked;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/6/11 1:35 下午
 */
public class SingleLinkedList {

    private Node head;
    private int size = 0;

    class Node {
        int value;
        Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public void remove(int element) {
        Node tmp = head;
        //头结点的删除
        if (head.value == element) {
            if (head.next != null) {
                head = head.next;
            } else {
                head.value = 0;
            }
        }
        while (tmp.next != null) {
            if (tmp.next.value == element) {
                tmp.next = tmp.next.next;
                size--;
            }
            tmp = tmp.next;

        }

    }
    public void add(int value) {
        Node node = new Node(value);
        if (head == null) {
            //初始化头结点
            head = node;
        } else {
            //如果头结点有数据，则遍历到最后一个节点
            Node tmp = head;
            while (tmp.next != null) {
                tmp = tmp.next;
            }
            tmp.next = node;
        }
        size++;
    }

    public void replaceAll(int oldElement, int newElement) {
        Node tmp = head;
        while (tmp != null) {
            if (tmp.value == oldElement) {
                tmp.value = newElement;
            }
            tmp = tmp.next;
        }
    }

    public void display(Node node) {
        for (int i = 0; i < size; i++) {
            System.out.print(" " + node.value);
            node = node.next;
        }
        System.out.println("\n");
    }

    public int size() {
        return size;
    }

    public static void main(String[] args) {
        SingleLinkedList singleLinkedList = new SingleLinkedList();
        for (int i = 0; i < 10; i++) {
            singleLinkedList.add(i);
            singleLinkedList.display(singleLinkedList.head);
            singleLinkedList.add(7);

        }
        singleLinkedList.replaceAll(7,100);
        singleLinkedList.remove(3);
        singleLinkedList.remove(5);
        singleLinkedList.display(singleLinkedList.head);
    }

}
